package com.squareshoot.picCheckin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class FriendsAndPhotos extends TabActivity {

	private static final float DISTANCE_DIP = 16.0f;
	private static final float PATH_DIP = 40.0f;
	private int minScaledVelocity;
	GestureDetector detector;

	DefaultHttpClient httpclient;
	String username,password,picuserid,nomPrenom,fsid,email;
	Bitmap userPic;
	boolean me;
	ArrayList<String> friends;
	ArrayList<String> myPhotosArray;
	Handler handler;
	Handler handlerPhotos;
	Runnable updateAdapter = null;
	ListView listFriends;
	PhotosAdapter adapterPhotos;
	UsersListAdapter adapterFriends;
	String myPhotos;
	private GetFriendsTask friendsTask;
	
	LinearLayout myProfileLoading,myProfilePhotosLoading;

	TabHost tabHost;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"MyProfile : onCreate");
		setContentView(R.layout.friendsandphotos);

		httpclient = new DefaultHttpClient();
		Cookie cookie = Common.recupCookie(this);
		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"cookie : "+cookie);
		httpclient.getCookieStore().addCookie(cookie);
		httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);

		Bundle bundle = getIntent().getExtras();
		nomPrenom = bundle.getString("nomPrenom");
		userPic = Common.getRoundedCornerBitmap((Bitmap)bundle.getParcelable("photo"));
		username = bundle.getString("username");
		password = bundle.getString("password");
		picuserid = bundle.getString("picuserid");
		fsid = bundle.getString("fsid");
		if(bundle.containsKey("email"))
			email = bundle.getString("email");
		else email=null;
		me = bundle.getBoolean("me");

		Resources res = getResources();
		tabHost = getTabHost();
		TabHost.TabSpec spec;  // Resusable TabSpec for each tab
		spec = tabHost.newTabSpec("friends").setIndicator(getString(R.string.myFriendsButton),res.getDrawable(R.drawable.friendstab)).setContent(R.id.tabMyFriends);
		tabHost.addTab(spec);
		spec = tabHost.newTabSpec("photos").setIndicator(getString(R.string.myPhotosButton),res.getDrawable(R.drawable.photostab)).setContent(R.id.tabMyPhotos);
		tabHost.addTab(spec);

		myProfileLoading=(LinearLayout)findViewById(R.id.myProfileLoadingLinear);
		myProfilePhotosLoading=(LinearLayout)findViewById(R.id.myProfilePhotosLoadingLinear);
		minScaledVelocity = ViewConfiguration.get(this).getScaledMinimumFlingVelocity();
		detector = new GestureDetector( new SwipeDetector() );

		if(savedInstanceState==null){
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"friends vide. Recup sur 4sq");
			myProfileLoading.setVisibility(View.VISIBLE);
			myProfilePhotosLoading.setVisibility(View.VISIBLE);
			
			friendsTask = new GetFriendsTask();
			friendsTask.setActivity(this);
			friendsTask.execute(picuserid);
		}else{
			//			Log.d(Common.TAG,"friends pas vide. Tab : "+savedInstanceState.getString("currentTab"));
			friends = savedInstanceState.getStringArrayList("friends");
			myPhotosArray = savedInstanceState.getStringArrayList("myPhotos");
			if(friends!=null) 
				tabMyFriends();
			if(myPhotosArray!=null)
				tabMyPhotos();

			if(getLastNonConfigurationInstance()!=null){
				friendsTask=(GetFriendsTask) getLastNonConfigurationInstance();
				friendsTask.setActivity(this);
			}
		}
	}

	protected void onDestroy(){
		super.onDestroy();
		if(Common.HIGHDEBUG)
			Log.d(Common.TAG,"MyProfile : onDestroy");
	}

	protected void onSaveInstanceState(Bundle outState) {
		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"MyProfile : onSaveInstantState");
		outState.putStringArrayList("friends",friends);
		outState.putStringArrayList("myPhotos",myPhotosArray);
		outState.putString("currentTab",getTabHost().getCurrentTabTag());
	}

	public Object onRetainNonConfigurationInstance() {
		if(friendsTask!=null){
			friendsTask.setActivity(null);
		}
		return friendsTask;
	}

	private ArrayList<String> fillFriendsArray(String reponse){
		ArrayList<String> friendsArray = new ArrayList<String>();

		try {
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"reponse size: "+reponse.length());
			JSONObject jResult=new JSONObject(reponse);
			JSONArray jFriends = jResult.getJSONArray("friends");
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"numbers of friends: "+jFriends.length());

			for(int i=0;i<jFriends.length();i++){
				JSONObject user = jFriends.getJSONObject(i);
				String name = user.getString("firstname");
				if(user.has("lastname"))
					name+=" "+user.getString("lastname");

				JSONObject jUser = new JSONObject();
				jUser.put("name",name);
				jUser.put("photo", user.getString("photo"));
				jUser.put("fsid",user.getString("id"));
				if(user.has("email"))
					jUser.put("email",user.getString("email"));
				if( user.has("picuserid") ){
					jUser.put("picuserid",user.getString("picuserid"));
				}
				friendsArray.add(jUser.toString());
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return friendsArray;
	}

	protected void tabMyFriends(){
		((TextView)findViewById(R.id.friendsProfileName)).setText(nomPrenom);
		((ImageView)findViewById(R.id.friendsProfilePic)).setImageBitmap(userPic);

		listFriends = (ListView)findViewById(R.id.listFriends);
		adapterFriends = new UsersListAdapter(this,friends,true);
		listFriends.setAdapter(adapterFriends);
		setOnClickFriends(listFriends);
		setOnTouchFriends(listFriends);
	}

	private void setOnTouchFriends(final ListView listFriends){
		listFriends.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				detector.onTouchEvent(arg1);
				return false;
			}
		});
	}

	private void setOnClickFriends(final ListView listFriends){
		listFriends.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, final View view, final int position,long id) {
				Intent i=new Intent(FriendsAndPhotos.this,FriendsAndPhotos.class);
				Bundle bundle = new Bundle();
				bundle.putString("username",username);
				bundle.putString("password",password);
				try {
					final JSONObject user = new JSONObject(friends.get(position));
					if(Common.HIGHDEBUG)
						Log.d(Common.TAG,"friend : "+user);
					if(user.has("picuserid")){
						bundle.putString("picuserid",user.getString("picuserid"));
					}
					bundle.putString("fsid",user.getString("fsid"));
					if(user.has("email"))
						bundle.putString("email",user.getString("email"));

					ImageView userPhoto = (ImageView)view.findViewById(R.id.userAdapterPhoto);
					BitmapDrawable bmd = (BitmapDrawable)userPhoto.getDrawable();
					bundle.putParcelable("photo",bmd.getBitmap());

					bundle.putString("nomPrenom",user.getString("name"));
				}catch(JSONException e){
					if(Common.HIGHDEBUG)
						Log.d(Common.TAG,"Error JSON : "+e.getMessage());
				}
				bundle.putBoolean("me",false);
				i.putExtras(bundle);
				startActivity(i);
			}
		});
	}

	private void setPhotos(String friendphotos){
		myPhotos = friendphotos;
		myPhotosArray = new ArrayList<String>();
		try {
			JSONArray jCheckins = new JSONArray(myPhotos);
			int taille = jCheckins.length();
			for(int i=0;i<taille;i++){
				myPhotosArray.add(jCheckins.getString(i));
			}
		} catch (JSONException e) {
			if(Common.HIGHDEBUG)
				Log.w(Common.TAG,"Pas de photo");
			myPhotos=null;
			myPhotosArray=null;
		}
		tabMyPhotos();
	}

	private void tabMyPhotos(){
		((TextView)findViewById(R.id.photosProfileName)).setText(nomPrenom);
		((ImageView)findViewById(R.id.photosProfilePic)).setImageBitmap(userPic);

		ListView listPhotos = (ListView)findViewById(R.id.listMyPhotos);
		TextView noPhoto = (TextView)findViewById(R.id.noPhotos);
		Button shareButton = (Button)findViewById(R.id.shareButton);
		shareButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// AndroidManifest.xml must have the following permission:
				// <uses-permission android:name="android.permission.INTERNET"/>
				Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
				emailIntent.setType("plain/text"); 
				if(email!=null)
					emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email});  
				emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.mailSubject));  
				emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.mailText));  

				startActivity(Intent.createChooser(emailIntent, getString(R.string.sendmail)));
			}
		});
		if(picuserid==null){ //User pas sur le site
			listPhotos.setVisibility(View.GONE);
			noPhoto.setText(nomPrenom+" "+getString(R.string.userNotFound));
//			noPhoto.setVisibility(View.VISIBLE);
//			shareButton.setVisibility(View.VISIBLE);
			findViewById(R.id.noPhotoLayout).setVisibility(View.VISIBLE);
		}
		else if(myPhotosArray!=null){ //User sur le site, avec des photos
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"myPhotosArray non null : "+myPhotos);
			adapterPhotos = new PhotosAdapter(FriendsAndPhotos.this,myPhotosArray);
			listPhotos.setAdapter(adapterPhotos);
			setOnClickPhotos(listPhotos);
		}else{ //User sur le site mais pas de photo
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"myPhotosArray is null");
			if(!me){
				noPhoto.setText(R.string.noFriendPhoto);
			}
			listPhotos.setVisibility(View.GONE);
			findViewById(R.id.noPhotoLayout).setVisibility(View.VISIBLE);
//			noPhoto.setVisibility(View.VISIBLE);
		}

	}

	private void setOnClickPhotos(ListView photosList){
		photosList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
				JSONObject jPicture;
				try {
					jPicture = new JSONObject(myPhotosArray.get(position));
					String photoURL = Common.getBaseImgsUrl()+jPicture.getString("url");
					Intent i = new Intent(FriendsAndPhotos.this,FullscreenPicture.class);
					i.putExtra("uri", photoURL);
					startActivity(i);
				} catch (JSONException e) {
				}
			}
		});
	}


	class SwipeDetector extends SimpleOnGestureListener {
		@SuppressWarnings("unused")
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			int scaledDistance;
			int scaledPath;

			// get distance between points of the fling
			double vertical = Math.abs( e1.getY() - e2.getY() );
			double horizontal = Math.abs( e1.getX() - e2.getX() );

			// convert dip measurements to pixels
			final float scale = getResources().getDisplayMetrics().density;
			scaledDistance = (int) ( DISTANCE_DIP * scale + 0.5f );
			scaledPath = (int) ( PATH_DIP * scale + 0.5f );		

			// test vertical distance, make sure it's a swipe
			if ( vertical > PATH_DIP ) {
				return false;
			}
			// test horizontal distance and velocity
			else if ( horizontal > DISTANCE_DIP && Math.abs(velocityX) > minScaledVelocity ) {
				// right to left swipe
				if (velocityX < 0 ) {
					moveScreenLeft();
				}
				// left to right swipe
				else {
					moveScreenRight();
				}
				return true;
			}
			return false;
		}	
	}

	public boolean onTouchEvent(MotionEvent event) {
		if(Common.HIGHDEBUG)
			Log.v(Common.TAG,"onTouchEvent");
		detector.onTouchEvent(event);
		return true;
	}

	public void moveScreenLeft() {
		if(Common.HIGHDEBUG)
			Log.v(Common.TAG,"moveLeft on quitte le tab "+tabHost.getCurrentTab());
		tabHost.setCurrentTab(1);
	}

	public void moveScreenRight() {
		if(Common.HIGHDEBUG)
			Log.v(Common.TAG,"moveRight on quitte le tab "+tabHost.getCurrentTab());
		tabHost.setCurrentTab(0);
	}

	private void onThreadCompleted(Bundle data){
		myProfileLoading.setVisibility(View.GONE);
		myProfilePhotosLoading.setVisibility(View.GONE);
		if(!data.containsKey("eMessage")){
			friends = fillFriendsArray(data.getString("reponse"));
			tabMyFriends();
			if(data.containsKey("friendphotos")){
				setPhotos(data.getString("friendphotos"));
			}else
				tabMyPhotos();
		}else{
			Toast erreurToast = Toast.makeText(FriendsAndPhotos.this,data.getString("eMessage"),Toast.LENGTH_SHORT);
			erreurToast.setGravity(Gravity.CENTER, 0, 0);
			erreurToast.show();
		}
	}

	private class GetFriendsTask extends AsyncTask<String,String,Message>{
		private FriendsAndPhotos activity;
		private boolean completed=false;
		private Message msg;

		protected Message doInBackground(String... parameters) {
			Message msg = Message.obtain();
			Bundle data = new Bundle();
			String urlFriends = Common.getBaseUrl()+"/friends";
			String reponse = null;
			try {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("user", username));
				params.add(new BasicNameValuePair("password", password));
				params.add(new BasicNameValuePair("fsid",fsid));

				reponse = Common.postUrlData(httpclient, urlFriends,params);
				data.putString("reponse",reponse);

				if(parameters[0]!=null){
					String url=Common.getBaseUrl()+"/friendphotos";
					params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("userid",parameters[0]));

					reponse = Common.postUrlData(httpclient, url, params);
					if(reponse!=null) data.putString("friendphotos",reponse);
				}
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			msg.setData(data);
			return msg;
		}

		protected void onPostExecute(Message msg) {
			completed=true;
			this.msg=msg;
			if(activity!=null)
				endTask(msg);
		}

		private void setActivity(FriendsAndPhotos activity) {
			this.activity = activity;
			if ( completed ) {
				endTask(msg);
			}
		}

		private void endTask(Message msg){
			activity.friendsTask=null;
			activity.onThreadCompleted(msg.getData());
		}
	}
}
